package com.lenovo.newsapp.activity;

import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.PreferenceUtil;
import com.lenovo.newsapp.wl.MyConnectListener;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;

public class LoginActivity extends BaseActivity implements OnClickListener{
	
	private EditText usernameET, passwordET;
	private Button loginBtn;
	
	private String username, password;
	
	public static WLClient client;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		actionBar.hide();
//		PreferenceUtil.init(this);
		client = WLClient.createInstance(this);
		client.connect(new MyConnectListener());
		Locale locale = getResources().getConfiguration().locale;
		String defaultLanguage = locale.getLanguage();
		 switchLanguage(PreferenceUtil.getString("language", "en"));
		// 判断起始状态
		if (PreferenceUtil.getString("login", "").equals("true")) {
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		}
		setContentView(R.layout.activity_login);
		
		
	   

	    usernameET = (EditText) findViewById(R.id.login_username_et);
	    passwordET = (EditText) findViewById(R.id.login_password_et);
		loginBtn = (Button) findViewById(R.id.login_btn);
		loginBtn.setOnClickListener(this);
		
		Analytics.trackState("LoginActivity", null);
		
		Log.v(Const.DEBUG,"client--"+client);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Config.pauseCollectingLifecycleData();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Config.collectLifecycleData();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.login_btn){
			username = usernameET.getText().toString();
			password = passwordET.getText().toString();
			
			PreferenceUtil.commitString(Const.USERINFO, "lenovo");
//			PreferenceUtil.commitString("username", "guxl4");
//			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//			startActivity(intent);
//			finish();
			if(username.equals("")){
				Toast.makeText(getApplicationContext(), R.string.username_can_not_empty, Toast.LENGTH_SHORT).show();
			}else if(password.equals("")){
				Toast.makeText(getApplicationContext(), R.string.password_can_not_empty, Toast.LENGTH_SHORT).show();
			}else{
				Log.v("", "Const.isSuccessWLInit = " + Const.isSuccessWLInit);
				if(Const.isSuccessWLInit){
					doLogin(username, password);
				}else{
					Toast.makeText(getApplicationContext(), R.string.wl_init_failure_2, Toast.LENGTH_SHORT).show();
				}
			}
		}

	}
	
	private void doLogin(final String username, String password) {
		showLoadProgressBar();
		String adapterName = "LoginAdapter";
		String procedureName = "login";
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		String deviceId = tm.getDeviceId();
		
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);
		Object[] parameters = new Object[] {username, password, "a", deviceId};
		invocationData.setParameters(parameters);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						final JSONObject jsonObj = response.getResponseJSON();
						Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj);
						handler.post(new Runnable() {

							@Override
							public void run() {
								try {
									Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj.getBoolean("authRequired"));
									if(jsonObj.getBoolean("authRequired") == false){
									JSONObject result = jsonObj.getJSONObject("loginResult");
										Log.v(Const.DEBUG, "onSuccess--dataJson = " + result.getString("message"));
										if(result.getBoolean("isLogin") == true){
											Toast.makeText(getApplicationContext(), R.string.login_success,Toast.LENGTH_LONG).show();
											Intent intent = new Intent(LoginActivity.this, MainActivity.class);
											startActivity(intent);
											PreferenceUtil.commitString("login", "true");
											PreferenceUtil.commitString("username", username);
											finish();
										}
										
									}else{
										Toast.makeText(getApplicationContext(), R.string.login_invalid,Toast.LENGTH_LONG).show();
//										Toast.makeText(getApplicationContext(), jsonObj.getString("errorMessage"), Toast.LENGTH_SHORT).show();
									}
//									Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj.getString("loginResult"));
//									showResult(jsonObj);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								hideLoadProgressBar();
							}

						});

					}

					public void onFailure(WLFailResponse response) {
						Log.v(Const.DEBUG, "onSuccess--dataJson = " + response);
//						String responseText = response.getResponseText();
						handler.post(new Runnable() {

							@Override
							public void run() {
								Toast.makeText(getApplicationContext(), R.string.login_failure,Toast.LENGTH_LONG).show();
								hideLoadProgressBar();
							}

						});
					}

				}, null);

	}

}
